<template>
  <div>
    <el-form label-width="80px" :model="page" ref="form">
      <el-row :gutter="24">
        <el-col :span="18">
          <el-col :span="24" :xs="24">
            <el-form-item :label="$t('APP名称')" prop="productName" :rules="[
                { required: true, message: $t('请选择APP'),},
              ]" style="width: 100%;">
              <el-col :span="7" :xs="24" style="padding: 0">
                <el-select v-model="page.productName" :placeholder="$t('请选择APP')"
                           @change="productChange" style="width: 100%">
                  <el-option v-for="item in productList" :key="item.productId" :value="item.productName"
                             :label="item.appName"></el-option>
                </el-select>
              </el-col>
              <div v-show="page.type">
                <el-col :span="1" style="text-align: center;line-height: 32px">-</el-col>
                <el-col :span="7" style="padding: 0 ">
                  <el-form-item prop="auditId" label-width="0px" style="margin-bottom: 0">
                    <el-select v-model="page.type" @change="auditIdSelect" style="width: 100%">
                      <el-option :value="1" :label="$t('初审')"></el-option>
                      <el-option :value="2" :label="$t('终审')"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </div>
              <el-col :span="1" style="text-align: center;line-height: 32px">-</el-col>
              <el-col :span="7" :xs="24" style="padding: 0;">
                <el-form-item prop="auditId" :rules="rulesAudit" label-width="0px" style="margin-bottom: 0">
                  <el-select v-model="page.auditId" :placeholder="$t('请选择信审员')" style="width: 100%;"
                  >
                    <el-option v-for="item in anditList" :key="item.adminUserId" :value="item.adminUserId"
                               :label="item.adminName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item :label="$t('订单编号')" prop="loanRecordId">
              <el-input v-model="page.loanRecordId" clearable/>

            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item :label="$t('用户姓名')" prop="name">
              <el-input v-model="page.name" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item :label="$t('手机号码')" prop="phone">
              <el-input v-model="page.phone" clearable/>
            </el-form-item>
          </el-col>

          <el-col :span="8" :xs="24">
            <el-form-item :label="$t('用户状态')" prop="isRepeatedBorrowing">
              <el-select style="width: 100%" v-model="page.isRepeatedBorrowing" clearable>
                <el-option :value="0" :label="$t('初借')"></el-option>
                <el-option :value="1" :label="$t('复借')"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24" v-show="isManagerRole">
            <el-form-item :label="$t('分配状态')" prop="undistributedOrder">
              <el-select style="width: 100%" v-model="page.undistributedOrder">
                <el-option :value="null" :label="$t('已分配')"></el-option>
                <el-option :value="1" :label="$t('业务未分配')"></el-option>
                <el-option :value="2" :label="$t('流程未分配')"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="6" :xs="24">
          <el-form-item>
            <div style="text-align: right">
              <el-button type="primary" @click="getTableData()">{{ $t('查询') }}</el-button>
              <el-button @click="clearSearch()">{{ $t('重置') }}</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div>
      <el-row style="margin: 10px 0;text-align: right">
        <el-button type="primary" @click="distribution('select')">{{ $t('所选分配') }}</el-button>
        <el-button type="primary" @click="distribution('search')">{{ $t('所搜分配') }}</el-button>
      </el-row>
      <Table :loading="pageLoading" :table-data="tableData" :page="page" @handleSizeChange="handleSizeChange"
             @handleCurrentChange="handleCurrentChange" @handleSelectionChange="handleSelectionChange">
        <template slot="operate">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column v-for="item in tableColumn" :label="item.label" :prop="item.prop" :key="item.prop"
                           :align="item.align"></el-table-column>
        </template>
      </Table>
    </div>
    <!--    分配弹窗-->
    <Dialog
        width="60%"
        :title="visible.title"
        :visible.sync="visible.isShow"
        @close="closeVisible"
        @cancel="visible.isShow = false"
        @confirm="confirm"
        append-body>
      <el-form label-width="50px" ref="distributionForm" :model="distributionPage">
        <el-row :gutter="24">
          <el-col :span="9" :xs="24">
            <el-form-item :label="$t('姓名')" prop="adminName">
              <el-input v-model="distributionPage.adminName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9" :xs="24">
            <el-form-item :label="$t('账号')" prop="accountNumber">
              <el-input v-model="distributionPage.accountNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24" style="text-align: right">
            <el-button type="primary" @click="getAuditPersonnelTable">{{ $t('查询') }}</el-button>
            <el-button @click="resetDistribution">{{ $t('重置') }}</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-row style="margin-top: 10px">
        <Table :table-data="anditTableList" :page="false"
               max-height="400px"
               @handleSelectionChange="andiSelectionChange">
          <template slot="operate">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column v-for="item in distributionTableColumn" :label="item.label" :key="item.prop"
                             :prop="item.prop"
                             :align="item.align"></el-table-column>
          </template>
        </Table>
      </el-row>
    </Dialog>
  </div>
</template>

<script>
import {theSingleSearch, theSingleDispose,} from '@/api/order'
import {selectAuditStaff} from "@/api/system";

export default {
  name: "transferOrder",
  props: {
    productList: {
      type: Array,
    },
  },
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        undistributedOrder: null,
      },
      pageLoading: false,
      anditTableList: [],
      anditList: [],
      selectRows: [],
      tableData: [],
      tableColumn: [
        {label: this.$t('订单编号'), prop: 'loanRecordId', align: 'center'},
        {label: this.$t('用户姓名'), prop: 'name', align: 'center'},
        {label: this.$t('手机号码'), prop: 'phone', align: 'center'},
        {label: this.$t('申请时间'), prop: 'loanTime', align: 'center'},
        {label: this.$t('申请金额'), prop: 'loanAmount', align: 'center'},
        // {label: this.$t('复借次数'), prop: 'loanNumber', align: 'center'},
        {label: this.$t('APP名称'), prop: 'appName', align: 'center'},
        {label: this.$t('信审员'), prop: 'auditName', align: 'center'},
      ],
      visible: {
        isShow: false,
        title: '',
        type: ''
      },
      distributionPage: {},
      distributionTableData: [],
      distributionTableColumn: [
        {label: this.$t('信审名称'), prop: 'adminName', align: 'center'},
        {label: this.$t('账号'), prop: 'accountNumber', align: 'center'},
      ],
      andiSelectRows: [],
    }
  },
  watch: {
    'page.undistributedOrder': function (val) {
      if (val === 1) {
        // 未分配状态去除信审员校验
        const fileds = this.$refs.form.fields
        for (let i = 0; i < fileds.length; i++) {
          if (fileds[i].prop === 'auditId') {
            fileds[i].resetField()
          }
        }
      }
    }
  },
  computed: {
    rulesAudit() {
      return this.page.undistributedOrder ? [] : [
        {required: true, message: this.$t('请选择信审员'),}
      ]
    },
    // 如果是经理角色隐藏分配状态
    isManagerRole() {
      return JSON.parse(sessionStorage.getItem('userInfo')).type !== 3
    },
  },
  methods: {
    async getTableData() {
      const fetch = async () => {
        this.pageLoading = true
        const params = {
          ...this.page,
        }
        const res = await theSingleSearch(params)
        if (res.code === 1) {
          const {list, total} = res.data
          this.tableData = list
          this.page = Object.assign({}, this.page, {
             total: total
          })
          this.pageLoading = false
        } else {
          this.tableData = []
          this.pageLoading = false
        }
      }
      this.$refs.form.validate(async v => {
        if (v) {
          if (!this.productName) return this.$message.error(this.$t('请先选择App'))
          fetch()
        }
      })

    },
    distribution(type) {
      if (type === 'select' && this.selectRows.length === 0) return this.$message.error('请勾选要分配的订单')
      this.$refs.form.validate(async v => {
        if (v) {
          await this.getAuditPersonnelTable()
          this.visible = {
            title: type === 'select' ? this.$t('所选分配') : this.$t('所搜分配'),
            type: type,
            isShow: true
          }
        }
      })

    },
    // 清空搜索框
    clearSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        undistributedOrder: null
      }
      this.anditList = []
      this.tableData = []
      this.$refs.form.resetFields()
    },
    closeVisible() {
      this.$refs.distributionForm.resetFields()
    },
    // app名称下拉
    productChange(value) {
      this.productName = value
      if (this.page.auditId) {
        this.$set(this.page, 'auditId', null)
      }
      this.getAuditPersonnelSelect()
    },
    //
    async auditIdSelect() {
      if (this.page.auditId) this.page.auditId = null
      this.anditList = await selectAuditStaff({
        productName: this.productName,
        ...this.page
      }).then(res => res.data)
    },
    // 获取分配表格信审员列表
    async getAuditPersonnelTable() {
      const {newIsFirstTrial, oldIsFirstTrial, isRepeatedBorrowing, type, undistributedOrder} = this.page
      const res = await selectAuditStaff({
        productName: this.productName,
        // 流程未分配type固定2
        type: undistributedOrder === 2 ? 2 : type,
        ...this.distributionPage,
        valid: 1,
        newIsFirstTrial, oldIsFirstTrial, isRepeatedBorrowing,
      })
     if(res.code === 1) {
       this.anditTableList = res.data
     }
    },
    // 获取下拉信审员列表
     getAuditPersonnelSelect() {
      const productItem = this.productList.find(item => item.productName === this.productName)
      const {newIsFirstTrial, oldIsFirstTrial} = productItem
      const params = {
        newIsFirstTrial,
        oldIsFirstTrial
      }
      const confirm = async (query) => {
        this.anditList = await selectAuditStaff({
          productName: this.productName,
          ...query
        }).then(res => res.data)
      }
      if (newIsFirstTrial === 0 && oldIsFirstTrial === 0) {
        this.page.type = null
        confirm(params)
      } else {
        params.type = 1
        confirm(params)
      }
      this.page = {...this.page, ...params}
    },
    // // 用户状态下拉
    // async userStatusSelect() {
    //   if (this.page.auditId) this.page.auditId = null
    //   this.$refs.form.validateField('isRepeatedBorrowing')
    //   const {
    //     newIsFirstTrial,
    //     oldIsFirstTrial,
    //     isRepeatedBorrowing,
    //     type
    //   } = this.page
    //   this.anditList = await getAuditPersonnel({
    //     productName: this.productName,
    //     newIsFirstTrial,
    //     oldIsFirstTrial,
    //     isRepeatedBorrowing, type
    //   })
    // },
    // 信审员全选
    andiSelectionChange(value) {
      this.andiSelectRows = value
    },
    // 清空分配弹窗
    resetDistribution() {
      this.distributionPage = {}
      this.$refs.distributionForm.resetFields()
      this.getAuditPersonnelTable()
    },
    clearForm() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        undistributedOrder: null
      }
      this.anditList = []
      this.$refs.form.resetFields()
    },
    async confirm() {
      if (this.andiSelectRows.length === 0) return this.$message.error(this.$t('请勾选信审员'))
      const auditIds = this.andiSelectRows.map(item => item.adminUserId)
      const loanRecordIds = this.selectRows.map(item => item.loanRecordId)
      let params = {}
      if (this.visible.type === 'select') {
        // 所选分配
        params = {
          loanRecordIds: loanRecordIds,
          auditIds: auditIds,
          ...this.page
        }
      } else {
        // 所搜分配
        params = {
          auditIds: auditIds,
          checkAll: 1,
          ...this.page
        }
      }
      const res = await theSingleDispose(params)
      if (res.code === 1) {
        this.$message.success(this.$t('操作成功'))
        this.andiSelectRows = []
        this.getAuditPersonnelTable()
        this.getTableData()
        // 通知父组件刷新列表
        this.$emit('confirm')
        this.visible.isShow = false
      }
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    // 订单编号
    handleSelectionChange(val) {
      this.selectRows = val
    },

  }
}
</script>

<style scoped>

</style>
